import pandas as pd
import yaml

from yaml import SafeLoader
from datareport.api import ImageUtil
from datareport.api.DataSource import DataSource
from datareport.impl import StaticDF
from datareport.impl.paragraph.base.BaseParagraph import BaseParagraph
from datareport.api.annotation.Style import style

@style()
class KaiZhanQingKuang_zhuti_zhengti_44(BaseParagraph):
    """
    组织生活开展主题分析-整体情况
    """

    def __init__(self):
        super().__init__()
        self.text = '''1 、 整 体 情 况 ： 在 支 委 会的工作 中 ，{} ％ 的 支 委 会\
在 讨 论 {}等 ，{}％ 的 支 委 会围 绕 {}专 题。 在 党 课 学 习 中 ， 主 要 围 绕{}等 专 题 。\
在 党 员 大 会 中 ，{} ％ 的 围 绕 {}专题 开 展 ，此 外 还 包 括{} 等 。在 其 他 组织 生 活 中 ，\
各基 层 党 组 织 开 展 了 各 类 主 题 党 日 活 动 ， 包 括 围 绕 “{}" 等 专 题 开 展 的 {}'''
        self.sort = 34
        self.section = 14

    def plot(self, df, plt):
        pass

    def getData(self, result):
        pass

    def start(self, conn, year, plt):
        self.text = self.text.replace(' ', '').replace('\n','')
        df = pd.read_sql('''select p.name,p.partyOrgName,
        (select name from t_podict where value=p.type) type,r.topicLabel 
        from t_meetinginfo p inner join t_meetingrecord r on r.meetingInfoId=p.id where year(startTime)={}'''.format(year), con=conn)
        topics = pd.read_sql('''select name,value from t_podict where type=\'topicLabel\'''', con=conn)
        ## 支委会最大，最小专题数
        if len(df[df['type'] == '支委会'])==0:
            zw_max_per=0
            zw_min_per=0
            zw_max_top=[]
            zw_min_top=[]
        else:
            zw_arr=df[df['type'] == '支委会']['topicLabel'].values
            zw_max_top,zw_max_per,zw_min_top,zw_min_per = parse(zw_arr,topics)
        ## 党课最大
        if len(df[df['type'] == '党课'])==0:
            dk_topics=[]
        else:
            dk_df=df[df['type'] == '党课']['topicLabel'].values
            dk_topics,_,_,_ = parse(dk_df,topics)
        ## 党员大会
        if len(df[df['type'] == '党员大会'])==0:
            dydh_max_top=[]
            dydh_max_per=0
        else:
            dydh_df=df[df['type'] == '党员大会']['topicLabel'].values
            dydh_max_top,dydh_max_per,_,_ = parse(dydh_df,topics)

        topicLabel_list = df[df['type'] == '党员大会']['topicLabel'].values.tolist()
        topicLabel_list=toStr(topicLabel_list,topics)
        dydh_top=[]
        for topstr in topicLabel_list:
            for item in topstr.split(','):
                if item not in dydh_max_top and item not in dydh_top:
                    dydh_top.append(item)

        ## 其他
        if len(df[df['type'].isin(['党员大会', '党课', '支委会']) == False])==0:
            qt_top=0
        else:
            qt_df=df[df['type'].isin(['党员大会', '党课', '支委会']) == False]['topicLabel'].values
            qt_top,_,_,_ = parse(qt_df,topics)
            name = df[df['type'].isin(['党员大会', '党课', '支委会']) == False]['name'].drop_duplicates().tolist()

        self.text = self.text.format(zw_max_per, list2str(zw_max_top),
                                     zw_min_per,list2str(zw_min_top),
                                     list2str(dk_topics),
                                     dydh_max_per,list2str(dydh_max_top),list2str(dydh_top),
                                     list2str(qt_top),list2str(name))
        # self.fonts.append(Font(text=self.text,color=ColorEnum.RED.value))
        values=[]
        orgs=df['partyOrgName'].drop_duplicates().tolist()
        for o in orgs:
            values.append(len(df[(df['partyOrgName']==o) & (df['topicLabel'].str.contains('2001'))]))
        self.image=ImageUtil.plot(pd.DataFrame(columns=['党组织','教学专题'],data = {'党组织': orgs, '教学专题': values}),ylable='二级党组织教学专题数')
        StaticDF.data=df

def toStr(values,topics):
    names = topics['name'].values.tolist()
    value = []
    for va in values:
        if va is None:
            continue
        temp = va.split(',')
        for v in temp:
            if len(topics[topics['value'] == v]) > 0:
                name = topics.loc[topics['value'] == v, 'name'].values[0]
                value.append(name)

    return value

def parse(values,topics):
    names = topics['name'].values.tolist()
    counts = [0] * len(names)
    for va in values:
        if va is None:
            continue
        temp = va.split(',')
        for v in temp:
            if len(topics[topics['value'] == v]) > 0:
                name = topics.loc[topics['value'] == v, 'name'].values[0]
                counts[names.index(name)] += 1
    max_count_per=round(100*max(counts)/sum(counts),1)
    min_count_per=round(100*min(counts)/sum(counts),1)
    max_count_indices = [i for i, count in enumerate(counts) if count == max(counts)]
    max_count_name = [names[i] for i in max_count_indices]
    min_count_indices = [i for i, count in enumerate(counts) if count == min(counts)]
    min_count_name = [names[i] for i in min_count_indices]
    return max_count_name,max_count_per,min_count_name,min_count_per

def list2str(l):
    return '、'.join(l)


if __name__ == '__main__':
    with open('D:\work\sanhuiyike\datareport\config.yaml', encoding='utf-8') as f:
        data = yaml.load(f, Loader=SafeLoader)
    con = DataSource(data['datasource']).conn
    KaiZhanQingKuang_zhuti_zhengti_44().start(con, 2023, '')
